<template>
	<div id="app">
		<h2>{{ message }}</h2>
		<el-upload action accept=".xlsx, .xls" :auto-upload="false" :show-file-list="false" :on-change="handle"><el-button type="primary">打开excel</el-button></el-upload>
		<div id="drop-area" :class="dropActive ? 'drop-active' : ''"><p>将文件拖拽到此处即可完成文件上传。</p></div>
		<el-table :data="tableData" border style="width: 100%">
			<el-table-column v-for="(name, index) in tabKeyName" :key="index" :prop="name" :label="name"></el-table-column>
		</el-table>
	</div>
</template>
+
<script>
import * as XLSX from 'xlsx/xlsx.mjs';
export default {
	name: 'App',
	data() {
		return {
			message: ' XLSX 导入解析 的使用',
			tableData: [],
			tabKeyName: [],
			dropActive: false
		};
	},
	mounted() {
		// excel解析配置项
		let dropArea = document.getElementById('drop-area');
		dropArea.addEventListener('drop', this.dropEvent, false);
		dropArea.addEventListener('dragleave', e => {
			e.stopPropagation();
			e.preventDefault();
			this.dropActive = false;
		});
		dropArea.addEventListener('dragenter', e => {
			e.stopPropagation();
			e.preventDefault();
			this.dropActive = true;
		});
		dropArea.addEventListener('dragover', e => {
			e.stopPropagation();
			e.preventDefault();
			this.dropActive = true;
		});
	},
	methods: {
		readFile(file) {
			//文件读取
			return new Promise(resolve => {
				let reader = new FileReader();
				reader.readAsBinaryString(file); //以二进制的方式读取
				reader.onload = ev => {
					resolve(ev.target.result);
				};
			});
		},
		// 文件传到此处 进行解析
		async handle(ev, upFile) {
			let file;
			if (ev) {
				file = ev.raw;
			} else {
				file = upFile;
			}
			if (!file) {
				console.error('文件打开失败');
				return;
			} else {
				let data = await this.readFile(file);
				let workbook = XLSX.read(data, { type: 'binary' }); //解析二进制格式数据
				let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet
				let result = XLSX.utils.sheet_to_json(worksheet); //json数据格式
				console.log(result);
				// result为最后解析出来的数据 !!!!
				this.tabKeyName = Object.keys(result[0]);
				this.tableData = result;
			}
		},
		// 拖拽  用按钮的话下面的可以不去看
		dropEvent(e) {
			this.dropActive = false;
			e.stopPropagation();
			e.preventDefault();
			this.uploadFile(e.dataTransfer.files);
		},
		// 用按钮的话可以不去看
		uploadFile(file) {
			// 渲染上传文件
			if (file && file.length) {
				//自行发挥，存本地或上传服务器
				this.handle(null, file[0]);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
#app {
	align-items: center;
	text-align: center;
}
#drop-area {
	margin: 20px 0;
	width: 400px;
	height: 50px;
	color: rgba(0, 0, 0, 0.45);
	text-align: center;
	background-color: #fafafa;
	border: 1px dashed #d9d9d9;
	text-align: center;
}
.drop-active {
	background-color: rgba(231, 234, 246, 0.8);
}
</style>
